﻿#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    pictureLocation=QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);

    QString videoLocation=QStandardPaths::writableLocation(QStandardPaths::MoviesLocation);
    recordLocation=videoLocation + "/Record";

    QDir dir(recordLocation);
    if(!dir.exists())
        dir.mkpath(recordLocation);

    info =nullptr;
    camera=nullptr;
    viewer=nullptr;
    imageCapture=nullptr;
    preview=nullptr;

    mediaRecorder=nullptr;

    if(QCameraInfo::availableCameras().count() > 0)
    {
        camera=new QCamera(QCameraInfo::defaultCamera());
        cameraDesc=QCameraInfo::defaultCamera().description();
        viewer=new QCameraViewfinder;
        camera->setViewfinder(viewer);
        currentResolution=RES_720P;

        setDefaultSetting();

        setCentralWidget(viewer);
        viewer->show();
        camera->start();

        ui->statusBar->showMessage(cameraDesc);
    }
    else
        ui->statusBar->showMessage(QStringLiteral("没有可用摄像头"));
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::keyPressEvent(QKeyEvent *event)
{
    switch (event->key()) {
    case Qt::Key_Space:
    {
        if(mediaRecorder == nullptr)
            return;

        if(mediaRecorder->state() == QMediaRecorder::RecordingState)
            mediaRecorder->stop();
    }
        break;
    }
}

void MainWindow::setDefaultSetting()
{
    QCameraViewfinderSettings viewfinderSettings;
    viewfinderSettings.setResolution(currentResolution);
    camera->setViewfinderSettings(viewfinderSettings);

    ui->statusBar->showMessage(QStringLiteral("当前分辨率：720P"));
}


void MainWindow::setCurrentOutputFile()
{
    QString currentTime=QDateTime::currentDateTime().toString("yyMMdd-hhmmss");
    QString location=recordLocation + "/" + currentTime + QString(".mp4");
    mediaRecorder->setOutputLocation(QUrl::fromUserInput(location));
}

QList<QVideoFrame::PixelFormat> MainWindow::getSupportedPixelFormats()
{
    return camera->supportedViewfinderPixelFormats();
}

QList<QSize> MainWindow::getSupportedResolutions()
{
    return camera->supportedViewfinderResolutions();
}

void MainWindow::imageSaved(int id, const QString &fileName)
{
    if(id == captureId)
        ui->statusBar->showMessage(QStringLiteral("图像已保存为：") + fileName);
}

void MainWindow::on_actionRecord_triggered()
{
    if(mediaRecorder == nullptr)
    {
        mediaRecorder=new QMediaRecorder(camera);
        connect(mediaRecorder,&QMediaRecorder::stateChanged,
                this,&MainWindow::stateChanged);
    }

    QVideoEncoderSettings videoSettings;
    videoSettings.setCodec("video/mpeg2");
    videoSettings.setQuality(QMultimedia::HighQuality);
    videoSettings.setResolution(currentResolution);
    mediaRecorder->setVideoSettings(videoSettings);
    mediaRecorder->setContainerFormat("mp4");

    qDebug() << mediaRecorder->supportedVideoCodecs();
    qDebug() << mediaRecorder->supportedContainers();
    qDebug() << mediaRecorder->supportedResolutions();
    setCurrentOutputFile();

    camera->setCaptureMode(QCamera::CaptureVideo);
    camera->start();
    ui->statusBar->showMessage("录制已开始……");

    //on shutter button pressed
    mediaRecorder->record();

    // sometime later, or on another press
    // mediaRecorder->stop();
}

void MainWindow::on_actionInfo_triggered()
{
    if(info==nullptr)
    {
        info=new CameraInfoDialog(this);
        info->appendAvailableCameraInfo();
        info->appendPixelFormatInfo(getSupportedPixelFormats());
        info->appendResolutionInfo(getSupportedResolutions());
    }
    info->show();
}

void MainWindow::imageCaptured(int id, const QImage &image)
{
    if(id == captureId)
        preview->updateView(image);
}

void MainWindow::on_actionCapture_triggered()
{
    if(imageCapture ==nullptr)
    {
        imageCapture=new QCameraImageCapture(camera);
        connect(imageCapture,&QCameraImageCapture::imageSaved,this,&MainWindow::imageSaved);
    }

    if(preview == nullptr)
    {
        preview = new CaptureView(this);
        connect(imageCapture,&QCameraImageCapture::imageCaptured,this,&MainWindow::imageCaptured);
    }

    camera->setCaptureMode(QCamera::CaptureStillImage);
    camera->start();
    //on half pressed shutter button
    camera->searchAndLock();

    //on shutter button pressed
    captureId=imageCapture->capture();

    //on shutter button released
    camera->unlock();

    int xPos=this->x() + this->frameGeometry().width() + 10;
    preview->move(xPos,this->y());
}

void MainWindow::on_actionPicture_triggered()
{
    QDesktopServices::openUrl(QUrl(pictureLocation));
}

void MainWindow::on_action720P_triggered()
{
    if(currentResolution == RES_720P)
        return;

    currentResolution = RES_720P;

    QCameraViewfinderSettings viewfinderSettings;
    viewfinderSettings.setResolution(currentResolution);
    camera->setViewfinderSettings(viewfinderSettings);
}

void MainWindow::on_action1080P_triggered()
{
    if(currentResolution == RES_1080P)
        return;

    if(!camera->supportedViewfinderResolutions().contains(RES_1080P))
    {
        ui->statusBar->showMessage(QStringLiteral("不支持的分辨率"));
        return;
    }

    currentResolution=RES_1080P;

    QCameraViewfinderSettings viewfinderSettings;
    viewfinderSettings.setResolution(currentResolution);
    camera->setViewfinderSettings(viewfinderSettings);
    ui->statusBar->showMessage(QStringLiteral("当前分辨率：1080P"));
}

/*
void MainWindow::on_actionVideo_triggered()
{
    QDesktopServices::openUrl(QUrl(recordLocation));
}
*/

void MainWindow::stateChanged(QMediaRecorder::State state)
{
    switch (state) {
    case QMediaRecorder::RecordingState:
        ui->statusBar->showMessage(QStringLiteral("录制中……"));
        break;
    case QMediaRecorder::PausedState:
        break;
    case QMediaRecorder::StoppedState:
        ui->statusBar->showMessage(QStringLiteral("已停止"));
        break;
    }
}
